package com.lelouch.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 尝试获取信号量
 *
 * @author lcy
 * @create 2018-05-29 10:09
 */
@Slf4j
public class SemaphoreExample3 {


    private final static int threadCount = 21;

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < threadCount; i++) {
            final int number = i;
            executorService.execute(() -> {


                if (semaphore.tryAcquire(3)) {
                    test(number);
                    semaphore.release(3);
                }

            });
        }
        log.info("finish");
        executorService.shutdown();
    }

    public static void test(int threadNum) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("count:{}", threadNum);
    }


}
